import { App, Form, Button, Input } from 'antd'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import type { WhitelistCorp } from '@/services/features/corp-whitelist'

export function Edit(props: { editing: true | WhitelistCorp | null; onFinish: () => void }) {
  const { editing, onFinish } = props
  return <EditModal
    title={editing === true ? '添加企微主体' : '编辑企微主体'}
    width={550}
    open={editing !== null}
    onCancel={onFinish}
  >
    {editing !== null ? (
      <EditContent item={editing === true ? undefined : editing} onFinish={onFinish} />
    ) : null}
  </EditModal>
}

function EditContent(props: { item?: WhitelistCorp; onFinish: () => void }) {
  const { item, onFinish } = props
  const { message } = App.useApp()

  const [saving, setSaving] = useState(false)
  async function save(values: { corpid: string; desc?: string }) {
    const id = item?.id
    const corpid = values.corpid.trim()
    const desc = values.desc?.trim() ?? ''

    setSaving(true)
    const result = await services.features.corpWhitelist.addOrUpdate({ id, corpid, desc })
    setSaving(false)

    if (result === true) {
      void message.success('保存成功')
      onFinish()
    } else {
      void message.warning(`保存失败：${result}`)
    }
  }

  return <Form
    labelCol={{ span: 4 }}
    onFinish={save}
    initialValues={{ corpid: item?.corpid, desc: item?.desc }}
  >
    <main>
      <Form.Item label="CorpId" name="corpid" rules={[{ required: true }]}>
        <Input placeholder="输入企微主体的 CorpId" />
      </Form.Item>
      <Form.Item label="描述" name="desc">
        <Input placeholder="输入描述" />
      </Form.Item>
    </main>
    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" htmlType="submit" loading={saving}>
        保存
      </Button>
    </footer>
  </Form>
}
